<?php
/**
 * Created by PhpStorm.
 * User: thanatos
 * Date: 2017/12/2
 * Time: 下午4:54
 */

namespace frontend\controllers;

use common\helpers\AjaxHelper;
use common\models\OrderForm;
use EasyWeChat\Payment\Order;
use Yii;
use common\models\Goods;

class GoodsController extends BaseController{
    /**
     * 诊疗项目列表
     */
    public function actionList()
    {
        // 查询购买产品的列表
        $list = Goods::find()->with('goodsExtra')->orderBy(['goods_id' => SORT_DESC])->all();
        return $this->render('list', ['list' => $list]);
    }
    
    public function actionInfo($id)
    {
        $info = Goods::findById($id);
        return $this->render('info', ['info' => $info]);
    }
    
    public function actionBuy()
    {
        $id = Yii::$app->request->getBodyParam('id');
    
        $model = new OrderForm(['goods_id' => $id, 'user_id' => Yii::$app->user->id]);
    
        $response = new AjaxHelper();
    
        if( $model->order() ){
            $payment = Yii::$app->wechat->app->payment;
            $wechatOrder = new Order([
                'openid' => Yii::$app->user->identity->wechat_id,
                'body' => '购买'. $model->getGoods()->goods_name,
                'out_trade_no' => $model->order_sn,
                'total_fee' => $model->price * 100,
                'trade_type' => "JSAPI",
                'notify_url' => Yii::$app->request->getHostInfo(). '/goods-buy.php',
            ]);
            $result = $payment->prepare($wechatOrder);
            if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
                $prepayId = $result->prepay_id;
                $json = $payment->configForPayment($prepayId, false);
                $response->data = $json;
            }else{
                $response->msg = '支付失败';
            }
        
        }else{
            $response->msg = $model->getErrors();
        }
        return $response;
    }
    
}